<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<div style="text-align: center">
    <input type="text" style="width: 500px;height: 40px;margin: 20px auto" onkeyup="seach(this.value)">
</div>
<div id="seachBox" style="width: 500px;margin: 0 auto;"></div>

<body id="body">
<script>
    function jsonpStr(url, arg, cb) {
        // 1拼接字符串  参数  如  id=1&name="小名"
        var queryString = "";
        for (var key in arg) {
            queryString += key + "=" + arg[key] + "&"
        }
        url += "?" + queryString;
        // 加上callback
        // 响应回来的有点（.）所以从第二位开始  截取
        var cbName = 'jsonp_' + Math.random().toString().substr(2);
        //window.jsonp_2182192=callback;
        window[cbName] = function (data) {
            cb(data);
            document.body.removeChild(scriptElement);
        };
        url = url + 'cb=' + cbName;
        // 2创建script标签  并且把拼接后的URL放到src上
        var scriptElement = document.createElement('script');
        scriptElement.src = url;
        // 3.把script标签加入到页面里
        document.body.appendChild(scriptElement);
    }

    // jsonpStr("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su", {wd: 'angular'},
    //     function (data) {
    //         console.log(data)
    //
    //     })
// 只能发送get 不支持其他请求
    //不安全  xss攻击  不采用
    function jsonp({url, params, cb}) {
        return new Promise((resolve, reject) => {
            let script = document.createElement("script");
            window[cb] = function (data) {
                resolve(data);
               var body= document.getElementById("body")
                   body.removeChild(script);
            }
            console.log(cb)
            params = {...params, cb};//wd=b&cb=show
            let arrs = [];
            for (let key in params) {
                arrs.push(`${key}=${params[key]}`)
            }
            script.src = `${url}?${arrs.join('&')}`;
            document.body.appendChild(script);

        })
    }
function seach(wd){
    jsonp({
        url: "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
        params: {wd: wd},
        cb: "show"
    }).then(data => {
        var str=''
        for (let i=0;i<data.s.length;i++){
            str+="<div style='border: 1px solid'>"+(i+1)+'、'+data.s[i]+"</div>"
        }
        var seachBox=document.getElementById("seachBox");
        console.log(seachBox)
        seachBox.innerHTML=str;
    })
}

    seach({
        url: "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",
        params: {wd: "我是dragon"},
        cb: "show"
    }).then(data => {
        console.log(data)

    })



</script>
</body>

</html>